/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web.util;

/**
 *
 * @author kabad
 */
import java.sql.SQLException;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.lang.annotation.Annotation;
import java.util.Properties;
import javax.annotation.Resource;
import javax.naming.Context;

public class SendMailEspol {

    @Resource(name = "mail/MailEspol", type = Session.class)
    private Session mailSession;
    private String from;
    private String to;
    private String subject;
    private String text;

    public SendMailEspol(String to, String subject, String text) throws SQLException {
        this.to = to;
        this.subject = subject;
        this.text = text;
        this.from = from;
    }

    public void send() {
        try {
            System.out.println("mailSession    " + mailSession);
//            InitialContext ic = new InitialContext();
//            String snName = "java:comp/env/mail/MailFiec";
//             mailSession = (Session) ic.lookup(snName);
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.espol.edu.ec");
            props.put("mail.smtp.user", "kabad@espol.edu.ec");
//            Authenticator auth = new MiAutenticador();
            mailSession = Session.getInstance(props);
            InternetAddress fromAddress = null;
            InternetAddress toAddress = null;
            fromAddress = new InternetAddress("kabad@espol.edu.ec");
            toAddress = new InternetAddress(to);
            Message simpleMessage = new MimeMessage(mailSession);
            simpleMessage.setFrom(fromAddress);
//        simpleMessage.setFrom();
            simpleMessage.setRecipient(RecipientType.TO, toAddress);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(text);
            Transport.send(simpleMessage);
        }catch (MessagingException ex) {
            Logger.getLogger(SendMailEspol.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static class MiAutenticador extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("kabad@fiec.espol.edu.ec", "fiec1984");
        }
    }
}
